package cn.vehicle.utils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;

public class CameraSemaphore {

    private static final ConcurrentHashMap<String, Semaphore> semaphores = new ConcurrentHashMap<>();

    public static Semaphore getSemaphore(String cameraIp) {
        Semaphore semaphore = semaphores.get(cameraIp);

        if (semaphore == null) {
            synchronized (CameraSemaphore.class) {
                if (semaphore == null) {
                    semaphore = new Semaphore(1);
                    semaphores.put(cameraIp, semaphore);
                }
            }
        }
        return semaphore;

    }

    public static Boolean tryAcquire(String cameraIp) {
        Semaphore semaphore = getSemaphore(cameraIp);
        return semaphore.tryAcquire();
    }


    public static void release(String cameraIp) {
        Semaphore semaphore = getSemaphore(cameraIp);
        semaphore.release();
    }

}
